
/**
 * 氚云订单信息导入
 */
import { Provide, Inject } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
// const moment = require('moment');
const uuid = require("uuid");
const xlsx = require('node-xlsx');
const fs = require('fs');
import { FileUtils } from '../utils/file'
import { ProjectRecordModel } from '../entity/project_records.methods';
import { JsonConfigModel } from "../entity/json_config.method";
import { OrdersRecordsModel } from "../entity/orders_records.methods";
import { ProjectOrderContactModel } from '../entity/project_order_contact.methods';

@Provide()
export class ChuanyunImportFileService {
  @Inject()
  ctx: Context;
  @Inject()
  ProjectRecordModel: ProjectRecordModel;
  @Inject()
  JsonConfigModel: JsonConfigModel;
  @Inject()
  OrdersRecordsModel: OrdersRecordsModel;
  @Inject()
  ProjectOrderContactModel: ProjectOrderContactModel;

  @Inject()
  FileUtils: FileUtils

  /**
  * 氚云订单数据导入
  */
  async uploadOrdersFile(): Promise<any> {
    const { ctx } = this;
    // const userInfo = ctx.userInfo;
    // 获取文件
    const stream = ctx.files[0];
    // 文件流写本地文件
    const localPath = await this.FileUtils.fileStreamUpload(stream, uuid.v4());
    const excelData = xlsx.parse(localPath);
    let newArr = excelData[0]['data'];
    
    // 过滤掉excel中空的行
    newArr = newArr.filter((item) => item.length);
    const _tableTitle = newArr[0];
    //  获取对应字段下标
    const object_id_index = _tableTitle.findIndex((el) => el === 'ObjectId');
    const owner_name_index = _tableTitle.findIndex((el) => el === 'OwnerId');
    const order_name_index = _tableTitle.findIndex((el) => el === 'F0000010');
    const start_time_index = _tableTitle.findIndex((el) => el === 'F0000019');
    const end_time_index = _tableTitle.findIndex((el) => el === 'F0000020');
    const pm_name_index = _tableTitle.findIndex((el) => el === 'F0000022');
    const order_id_index = _tableTitle.findIndex((el) => el === 'SeqNo');
    const brand_name_index = _tableTitle.findIndex((el) => el === 'F0000123');

    newArr.splice(0, 2);
    //  查询在职员工列表
    const jobUser = await this.JsonConfigModel.getDataByCode('OnJobUser');
    let _users = [];
    if (jobUser && jobUser.length && jobUser[0].json_data) {
      let _arr = jobUser[0].json_data ? JSON.parse(jobUser[0].json_data) : [];
      for (let i = 0; i < _arr.length; i++) {
        _users.push(_arr[i])
      }
    }

    let successNum = 0;
    const errorRes = [];
    newArr.reverse();
    for (let i = 0; i < newArr.length; i++) {
      const item = newArr[i];
      if (item[object_id_index] && item[order_id_index] && item[order_name_index] && item[order_name_index].trim()) {
        //  查询当前订单是否已导入过
        const _res = await this.OrdersRecordsModel.chuanyunGetOrderByid(item[order_id_index]);
        //  查询PM用户unionid
        const pmUserObj = _users.filter(items => items.name === item[pm_name_index]);
        let pmUnionid = pmUserObj.length ? pmUserObj[0].unionid : "";
        let ownerUnionid = "";
        if (pmUnionid && item[pm_name_index] === item[owner_name_index]) {
          ownerUnionid = pmUnionid;
        } else {
          //  查询owner用户unionid
          const ownerUserObj = _users.filter(items => items.name === item[owner_name_index]);
          ownerUnionid = ownerUserObj.length ? ownerUserObj[0].unionid : ""
        }

        const order_obj = {
          chuanyun_object_id: item[object_id_index],
          chuanyun_owner_name: item[owner_name_index],
          chuanyun_owner_unionid: ownerUnionid,
          order_name: item[order_name_index] || "",
          chuanyun_start_time: item[start_time_index] || "",
          chuanyun_end_time: item[end_time_index] || "",
          chuanyun_pm_name: item[pm_name_index] || "",
          chuanyun_pm_unionid: pmUnionid,
          order_id: item[order_id_index],
          brand_name: item[brand_name_index] || ""
        }

        if (_res[0].total) {
          // 更新订单信息
          await this.OrdersRecordsModel.chuanyunUpdateOrder(order_obj);
          successNum++;
        } else {
          // 创建订单信息
          const insertRes = await this.OrdersRecordsModel.chuanyunInsertOrder(order_obj);

          //  氚云订单导入同时  创建项目信息
          //  创建项目信息
          const insertProj = await this.ProjectRecordModel.chuanyunInsertProject({
            project_name: order_obj.order_name,
            brand_name: order_obj.brand_name,
            user_id: order_obj.chuanyun_pm_unionid,
            user_name: order_obj.chuanyun_pm_name,
          });

          //  新增项目订单关联关系
          await this.ProjectOrderContactModel.insertContact({
            projId: insertProj.id,
            orderId: insertRes.id
          })
          successNum++;
        }
      } else {
        errorRes.push({ project_record_id: item[object_id_index], project_name: item[order_name_index] });
      }
    }

    //上传完成  删除临时文件
    fs.unlinkSync(localPath);
    return { successNum, errorRes, _tableTitle };
  }

}
